package com.vincent;

import org.apache.activemq.pool.PooledConnectionFactory;

import javax.jms.*;

/**
 * Created by vincent on 2018/7/29.
 */
public class ConsumerRunner implements Runnable {
    private PooledConnectionFactory pooledConnectionFactory;
    private String queueName;
    private String flag;

    public ConsumerRunner(PooledConnectionFactory pooledConnectionFactory, String queueName, String flag) {
        this.pooledConnectionFactory = pooledConnectionFactory;
        this.queueName = queueName;
        this.flag = flag;
    }

    @Override
    public void run() {
        System.out.println("------------------------"+flag);
        Session session = null;

        MessageConsumer consumer=null;
        Connection connection=null;
        try {
            connection = pooledConnectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            consumer = session.createConsumer(destination);
            while (true){
                Message message = consumer.receive(100);
                if (message != null){
                    System.out.println("线程"+flag +"接受到消息:"+((TextMessage) message).getText());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                consumer.close();
                session.close();
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
